package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDrawPrizeItem;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import com.lehecai.core.util.CoreStringUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import java.util.*;

/**
 * Created by zhangzq on 14-12-1.
 * 新疆风采35选7 官网抓取
 */
public class LotteryDrawFetch520WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    //如果彩期为null 则获取最新彩期
    private static final String BASE_URL = "http://www.xjflcp.com/servlet/queryLotteryDraw?game=35X7&num=1";
    private static final String RESULT_LOCALITY_URL = "http://www.xjflcp.com/video/prizeDetail.do?operator=detail357&lotterydraw=";

    public LotteryDrawFetch520WorkerOfficial (LotteryType lotterytype) {
        super(lotterytype);
    }


    @Override
    public LotteryDraw fetchResult(String phase) {
        return this.fetchResultDetail(phase);
    }

    @Override
    public LotteryDraw fetchResultDetail(String phase) {
        String url = this.getResultUrl(phase);	//获取详情地址
        if (url == null) {
            logger.error("无法解析到详情地址");
            return null;
        } else {
            logger.info("解析到的详情地址：{}",url);
        }

        String encoding = CharsetConstant.CHARSET_GB2312;
        String data = "";

        Map<String, String> headerParams = new HashMap<String, String>();
        headerParams.put("Referer", "http://www.bjfcdt.gov.cn");
        headerParams.put("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");

        try {
            data = CoreFetcherUtils.URLGetWithHeaderParams(url, headerParams, null, encoding);
        } catch (Exception e) {
            logger.error("get方式请求异常",e);
        }

        if (data == null || data.indexOf("404 Not Found") > 0 || data.isEmpty()) {
            logger.error( "data is null or 404 Not Found");
            return null;
        }
        LotteryDraw lotteryDraw = new LotteryDraw();
        Parser parser;
        NodeList nodeList;
        String fetchPhase = "";							//彩期
        String timeDraw = "";							//开奖日期
        String volumeOfSales = "";						//销售量
        String jackPot = "";							//奖池
        String result = "";								//开奖结果
        List<LotteryDrawPrizeItem> resultDetail = null;	//开奖详情
        NodeFilter tableFilter = new TagNameFilter("table");
        parser= Parser.createParser(data, encoding);
        try {
            nodeList = parser.extractAllNodesThatMatch(tableFilter);
            if (nodeList == null || nodeList.size() == 0) {
                logger.error("没有对应的table节点");
            } else {
                //获取开奖信息
                if (nodeList.size() > 0) {
                    TableTag tableTag = (TableTag)nodeList.elementAt(1);
                    TableRow[] tableRows = tableTag.getRows();
                    if (tableRows.length > 3) {
                        TableColumn[] fetchPhaseColumn = tableRows[0].getColumns();
                        if (fetchPhaseColumn.length > 3) {
                            fetchPhase = fetchPhaseColumn[1].getStringText();
                            timeDraw = fetchPhaseColumn[3].getStringText();
                        }
                        TableColumn[] drawBallColumn = tableRows[1].getColumns();
                        if (drawBallColumn.length > 1) {
                            NodeList nodeList1 = drawBallColumn[1].getChildren();
                            String result1 = "";
                            String result2 = "";
                            if (nodeList1 != null && nodeList1.size() > 1) {
                                result1 = nodeList1.elementAt(0).toPlainTextString();
                                result2 = nodeList1.elementAt(1).toPlainTextString().trim();
                            }
                            result = result1 + "" + result2;
                            String [] resultArray = result.replace("   "," ").replace("  "," ").trim().split(" ");
                            result = CoreFetcherUtils.mergeStringArray(resultArray, ",");
                        }
                        TableColumn[] volumeOfSalesColumn = tableRows[2].getColumns();
                        if (volumeOfSalesColumn.length > 0) {
                            if (StringUtils.isNotEmpty(volumeOfSalesColumn[0].getStringText())) {
                                volumeOfSales = CoreStringUtils.substringBetween(volumeOfSalesColumn[0].getStringText(), "本期新疆地区销售总额：", "元").trim();
                                volumeOfSales = volumeOfSales.replace(",","");
                            }
                        }
                        TableColumn[] jackPotColumn = tableRows[3].getColumns();
                        if (jackPotColumn.length > 0) {
                            jackPot = CoreStringUtils.substringBetween(jackPotColumn[0].getStringText(), "奖池累计金额：", "元").trim();
                            jackPot = jackPot.replace(",", "");
                        }
                    }
                }
                if (StringUtils.isNotEmpty(phase) && StringUtils.isNotEmpty(fetchPhase)) {
                    if (!phase.equals(fetchPhase)) {
                        logger.error("传入彩期与抓取彩期不一致，返回null");
                        return null;
                    }
                }
                //获取详情信息
                try {
                    resultDetail = new ArrayList<LotteryDrawPrizeItem>();
                    if (nodeList.size() > 1) {
                        TableTag tableTag = (TableTag)nodeList.elementAt(2);
                        TableRow[] tableRows = tableTag.getRows();
                        if (tableRows != null && tableRows.length > 7) {
                            for (int i = 1 ; i < tableRows.length; i++) {
                                LotteryDrawPrizeItem item = new LotteryDrawPrizeItem();
                                String name = "";			//奖级名称
                                String winningCount = "";	//中奖注数
                                String prizeAmount = "";	//中奖金额
                                TableColumn[] drawPrizeColumn = tableRows[i].getColumns();
                                if (drawPrizeColumn != null && drawPrizeColumn.length > 2) {
                                    name = drawPrizeColumn[0].getStringText();
                                    winningCount = drawPrizeColumn[1].getStringText().trim();
                                    prizeAmount = drawPrizeColumn[2].getStringText();
                                    if (StringUtils.isNotEmpty(prizeAmount)) {
                                        prizeAmount = prizeAmount.replace("元", "").trim();
                                    }
                                }
                                item.setName(name);
                                item.setWinningCount(winningCount);
                                item.setPrizeAmount(prizeAmount);
                                resultDetail.add(item);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("解析详细信息出现异常");
                    logger.error(e.getMessage(), e);
                }
                lotteryDraw.setLotteryType(this.getLotteryType());
                lotteryDraw.setPhase(fetchPhase);
                lotteryDraw.setResult(result);
                lotteryDraw.setTimeDraw(timeDraw);
                lotteryDraw.setVolumeOfSales(volumeOfSales);
                lotteryDraw.setJackpot(jackPot);
                lotteryDraw.setResultDetail(resultDetail);
            }
        } catch (ParserException e) {
            logger.error("解析开奖详情异常");
            logger.error(e.getMessage(), e);
        }
        return lotteryDraw;
    }

    @Override
    protected String getResultDetailUrl(String phase) {
        return null;
    }

    @Override
    protected String getResultUrl(String phase) {
        String url;
        //如果查询为null
        if (StringUtils.isEmpty(phase)) {
            String fetchPhase = "";
            try {
                String data;
                Map<String, String> headerParams = new HashMap<String, String>();
                headerParams.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
                headerParams.put("Content-Type","application/x-www-form-urlencoded");
                try {
                    data = CoreFetcherUtils.URLGet(BASE_URL, headerParams, CharsetConstant.CHARSET_UTF8);
                } catch (Exception e) {
                    logger.error("获取xml数据失败" + e.getMessage());
                    return null;
                }
                if (StringUtils.isEmpty(data) || data.indexOf("404 Not Found") > 0) {
                    logger.error(BASE_URL + "data is null or 404 Not Found");
                    logger.error("未获取到开奖详情信息列表！");
                    return null;
                }

                Document document = null;
                try {
                    document = DocumentHelper.parseText(data);
                } catch (DocumentException e) {
                    logger.error("解析开奖信息出现异常");
                    logger.error(e.getMessage(), e);
                }
                LotteryDraw lotteryDraw = new LotteryDraw();

                Element root = null;
                List<Element> elements = null;
                if (document != null) {
                    root = document.getRootElement();
                }
                if (root != null) {
                    elements = root.elements();
                }
                if (elements != null && elements.size() > 0) {
                    for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
                        Element element = it.next();
                        Element phaseElement = element.element("term0");
                        fetchPhase = phaseElement.getText().trim();
                        break;
                    }
                }
            } catch (Exception e) {
                logger.error("抓取彩期信息出现异常！");
                logger.error(e.getMessage(), e);
            }
            if (StringUtils.isEmpty(fetchPhase)) {
                return null;
            } else {
                url = RESULT_LOCALITY_URL + fetchPhase;
            }
        } else {
            url = RESULT_LOCALITY_URL + phase;
        }
        return url;
    }


    public static void main(String[] args) {
        String phase = null;

        AbstractLotteryDrawFetchWorker fetchWorker = new LotteryDrawFetch520WorkerOfficial(LotteryType.TJKL10);
        //抓取结果页面
        LotteryDraw resultListObj = fetchWorker.fetchResult(phase);
        //抓取详情页面
        LotteryDraw resultDetailObj = fetchWorker.fetchResultDetail(phase);
        LotteryDraw returnObj = CoreFetcherUtils.getComparedResult(null, resultDetailObj);

    }
}
